package com.zhongfl.crm.service.impl.boss;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zhongfl.crm.enums.boss.CommonLogType;
import com.zhongfl.crm.lixiao.mapper.CommonLogMapper;
import com.zhongfl.crm.service.boss.CommonLogAtomService;
import com.zhongfl.crm.model.boss.CommonLog;
import com.zhongfl.crm.util.ObjectCompareUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.heptagram.core.common.util.JsonUtil;

import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.lang.annotation.Annotation;

/**
 * @author wang.yuchuan
 * @date 2018/9/30
 */
@Service
@Slf4j
public class CommonLogAtomServiceImpl implements CommonLogAtomService {

    @Resource
    private ObjectCompareUtils objectCompareUtils;

    @Resource
    private CommonLogMapper commonLogMapper;

    @Override
    public void add(CommonLogType type, CommonLogType typeExt,
                    String key,
                    Object source,
                    Object target,
                    String user) throws JsonProcessingException, IntrospectionException {
        add(type, typeExt, key, source, target, user, null);
    }

    @Override
    public void add(CommonLogType type, CommonLogType typeExt,
                    String key,
                    Object source,
                    Object target,
                    String user,
                    final Class<? extends Annotation> compareAnnotationType) throws JsonProcessingException, IntrospectionException {
        ObjectCompareUtils.ObjectCompareResult compareResult = objectCompareUtils.compare(source, target, compareAnnotationType);
        CommonLog log = new CommonLog();
        log.setType(type);
        log.setTypeExt(typeExt);
        log.setKey(key);
        log.setBefore(JsonUtil.toJson(source));
        log.setAfter(JsonUtil.toJson(target));
        log.setMessage(compareResult.toString());
        log.setCreatedBy(user);
        commonLogMapper.insert(log);
    }

    @Override
    public void add(CommonLogType type, CommonLogType typeExt,
                    String key,
                    String msg,
                    String user) throws JsonProcessingException, IntrospectionException {
        CommonLog log = new CommonLog();
        log.setType(type);
        log.setTypeExt(typeExt);
        log.setKey(key);
        log.setMessage(msg);
        log.setCreatedBy(user);
        commonLogMapper.insert(log);
    }
}
